﻿using Furion;
using Furion.SpecificationDocument;
using Furion.VirtualFileServer;
using GnpFine.Core;
using GnpFine.Core.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using System.IO;

namespace Yjtest;

public class Startup : AppStartup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // 系统日志，重新定义日志服务， 涉及到数据库日志。所以放到后面了,详细的看GnpFine.StartUI.BackgroundServices这个项目的日志配置
        services.AddConsoleFormatter();
        services.AddFileLogging("logs/application.log");


        // 配置选项
        services.AddProjectOptions();

        // SqlSugar
        services.AddSqlSugar();



        // 允许跨域
        services.AddCorsAccessor();

        // 远程请求
        services.AddRemoteRequest();



        // 任务调度
        services.AddSchedule(options =>
        {
            options.AddPersistence<DbJobPersistence>(); // 添加作业持久化器
        });

        // Json序列化设置
        static void SetNewtonsoftJsonSetting(JsonSerializerSettings setting)
        {
            setting.DateFormatHandling = DateFormatHandling.IsoDateFormat;
            setting.DateTimeZoneHandling = DateTimeZoneHandling.Local;
            setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 时间格式化
            setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 忽略循环引用
            // setting.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 解决动态对象属性名大写
            // setting.NullValueHandling = NullValueHandling.Ignore; // 忽略空值
            // setting.Converters.AddLongTypeConverters(); // long转string（防止js精度溢出） 超过16位开启
            // setting.MetadataPropertyHandling = MetadataPropertyHandling.Ignore; // 解决DateTimeOffset异常
            // setting.DateParseHandling = DateParseHandling.None; // 解决DateTimeOffset异常
            // setting.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }); // 解决DateTimeOffset异常
        };

        services.AddControllersWithViews()
            .AddAppLocalization()
            .AddNewtonsoftJson(options => SetNewtonsoftJsonSetting(options.SerializerSettings))
            //.AddXmlSerializerFormatters()
            //.AddXmlDataContractSerializerFormatters()
            .AddInjectWithUnifyResult<AdminResultProvider>()
            ;

        // 系统日志
        //services.AddLoggingSetup();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        //// 启用HTTPS
        //app.UseHttpsRedirection();

        app.UseStaticFiles();

        app.UseRouting();

        app.UseCorsAccessor();

        app.UseAuthentication();
        app.UseAuthorization();

        // 配置Swagger-Knife4UI（路由前缀一致代表独立，不同则代表共存）
 /*       app.UseKnife4UI(options =>
        {
            options.RoutePrefix = "kapi";
            foreach (var groupInfo in SpecificationDocumentBuilder.GetOpenApiGroups())
            {
                options.SwaggerEndpoint("/" + groupInfo.RouteTemplate, groupInfo.Title);
            }
        });*/

        // 还可以配置生产环境关闭 定时任务管理器
        app.UseScheduleUI(options =>
        {
            options.RequestPath = "/myjob";
            options.DisableOnProduction = false;
        });

        app.UseInject();
        //app.UseInject(string.Empty);

        #region 启用静态网站技术
        app.UseDefaultFiles(new DefaultFilesOptions
        {
            RequestPath = new PathString("/wwwroot"),
            DefaultFileNames = new[] { "index.html" }
        });
        //支持默认文件（index.html）
        //静态文件访问
        app.UseStaticFiles(new StaticFileOptions
        {
            ContentTypeProvider = FS.GetFileExtensionContentTypeProvider(),

        });
        #endregion

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
